package com.zhang.servlet.renderCurrentUser;

import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhang.service.RenderCurrentService;
import com.zhang.util.Log;
import com.zhang.view_object.RenderCurrentUser;
import com.zhang.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author happy
 */
@WebServlet("/renderCurrentUserJSON")
public class RenderCurrentUserJSON extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final RenderCurrentService user = new RenderCurrentService();
    public RenderCurrentUserJSON() {
        // 目的是序列化出的JSON带有空格和换行,可以不写
        objectMapper.setDefaultPrettyPrinter(new DefaultPrettyPrinter());
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Log.println("访问 GET /renderCurrentUserJSON");

        req.setCharacterEncoding("utf-8");
        RenderCurrentUser resultView = new RenderCurrentUser();
        // 1.获取当前用户
        HttpSession session = req.getSession(false);
        UserVO currentUser = null;
        if (session != null) {
            currentUser = (UserVO) session.getAttribute("currentUser");
        }
        // 2.是否登录
        if(currentUser == null) {
            Log.println("用户未登录");
            resultView.currentUser=null;
        }else {
            Log.println("用户已登录" + currentUser);
            resultView = user.findUser(currentUser);
        }

        Log.println("JSON序列化对象"+resultView);
        // 使用Jackson提供代码,将list对象,转化成字符串类型的,JSON格式
        String json = objectMapper.writeValueAsString(resultView);
        Log.println("JSON 序列化后"+json);
        // 响应字符串
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        Log.println("JSON写入响应体");
        writer.println(json);
    }
}